package com.lqs.blog.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lqs.blog.dos.Archives;
import com.lqs.blog.mapper.ArticleBodyMapper;
import com.lqs.blog.mapper.ArticleMapper;
import com.lqs.blog.mapper.ArticleTagMapper;
import com.lqs.blog.pojo.*;
import com.lqs.blog.service.*;
import com.lqs.blog.utils.UserThreadLocal;
import com.lqs.blog.vo.ArticleVo;
import com.lqs.blog.vo.TagVo;
import com.lqs.blog.vo.param.ArticleParam;
import com.lqs.blog.vo.param.PageParams;
import com.lqs.blog.vo.Result;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service//注入spring容器
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleBodyService articleBodyService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ThreadService threadService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Override
    public Result listArticle(PageParams pageParams) {
        //根据文章归档来查询文章，需要手写sql
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> iPage = articleMapper.listArticle(
                page,
                pageParams.getTagId(),
                pageParams.getCategoryId(),
                pageParams.getYear(),
                pageParams.getMonth()
        );

        List<Article> articles = iPage.getRecords();
        return Result.success(copyList(articles, true, true));


//        //1.分页查询article数据库表
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
//        //判断
//        if (pageParams.getCategoryId() != null) {
//            wrapper.eq(Article::getCategoryId, pageParams.getCategoryId());
//        }
//        if (pageParams.getTagId() != null) {
////            List<Article> articles = articleMapper.getArticlesByTagId(pageParams.getTagId());
//            List<ArticleTag> articleTags = tagService.getTagsByTagId(pageParams.getTagId());
//            List<Long> article_ids = new ArrayList<>();
//            for (ArticleTag articleTag : articleTags) {
//                article_ids.add(articleTag.getArticleId());
//            }
//
//            if (article_ids.size() > 0) {
////                and in (article_ids)
//                wrapper.in(Article::getId, article_ids);
//            }
//
//        }
//        //查询条件，是否置顶进行排序，时间排序，倒叙
//        wrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
//
//        Page<Article> articlePage = articleMapper.selectPage(page, wrapper);
//
//        List<Article> records = articlePage.getRecords();//获取查询到的信息
////        System.out.println("records:" + records);
//
//        List<ArticleVo> articleVos = copyList(records, true, true);//进行数据转移
//        return Result.success(articleVos);

    }


    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        ArrayList<ArticleVo> articleVos = new ArrayList<>();
        for (Article record : records) {
            articleVos.add(copy(record, isTag, isAuthor));
        }
        return articleVos;
    }

    /**
     * BeanUtils.copyProperties("转换前的类", "转换后的类");
     *
     * @param article
     * @return
     */
    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);//复制相同属性
        //将long类型转换为String
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        articleVo.setId(article.getId().toString());
        if (isTag) {
            Long articleId = article.getId();//文章id
            //若文章有标签
            articleVo.setTags(tagService.getTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();//作者id
            //若文章有作者
            articleVo.setAuthor(sysUserService.getUserById(authorId).getNickname());
        }
        return articleVo;
    }

    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);//复制相同属性
        //将long类型转换为String
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        articleVo.setId(article.getId().toString());
        if (isTag) {
            Long articleId = article.getId();//文章id
            //若文章有标签
            articleVo.setTags(tagService.getTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();//作者id
            //若文章有作者
            articleVo.setAuthor(sysUserService.getUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            //通过bodyId查找对应body对象
            articleVo.setBody(articleBodyService.getById(bodyId));
        }
        if (isCategory) {
            //通过类别Id查找分类
            int categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.getById(categoryId));
        }
        return articleVo;
    }


    @Override
    public Result getHot(int limit) {
//        List<Article> articles = articleMapper.getArticlesByHot(limit);
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper();
        wrapper.select(Article::getId, Article::getTitle);//查询id和title
        wrapper.orderByDesc(Article::getViewCounts);//按照查看量降序查询
        wrapper.last("limit " + limit);

        List<Article> articles = articleMapper.selectList(wrapper);
//返回的是ArticleVo对象
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result getNewest(int limit) {
//        List<Article> articles = articleMapper.getArticlesByDate(limit);
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result listArchives() {
        //文章归档
        List<Archives> archives = articleMapper.getArchives();
        return Result.success(archives);
    }

    @Override
    public Result getArticleById(Long id) {
        Article article = articleMapper.selectById(id);
        ArticleVo articleVo = copy(article, true, true, true, true);
        //线程池 用于更新文章阅读数量  可以把更新操作扔到线程池中操作 和主线程不相关
        threadService.updateArticleViewCounts(articleMapper, article);
        return Result.success(articleVo);
    }

    @Override
    public Result publishArticle(ArticleParam articleParam) {
        //此接口要加入到登录拦截器中
        //获取当前作者
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id  当前的登录用户
         * 3. 标签  要将标签加入到 关联列表当中
         * 4. body 内容存储 article bodyId
         */
        Article article = new Article();
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setAuthorId(sysUser.getId());
        Integer categoryId = Integer.parseInt(articleParam.getCategory().getId());
        article.setCategoryId(categoryId);
        //插入之后 会生成一个文章id
        this.articleMapper.insert(article);//mybatis-plus自动返回参数得到文章id
        //tag
        List<TagVo> tagList = articleParam.getTags();
        if (tagList != null) {
            for (TagVo tagVo : tagList) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(Long.parseLong(tagVo.getId()));
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        //添加操作
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());
        //对文章更新
        articleMapper.updateById(article);

        HashMap<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }
}
